﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Mbs.Utils.Extension
{
    public static partial class Extensions
    {
        // 将DateTime转换为Unix时间戳（秒）
        public static long ToUnixTimeSeconds(this DateTime dateTime)
        {
            DateTime unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            return (long)(dateTime.ToUniversalTime() - unixEpoch).TotalSeconds;
        }
        public static async Task<T> TimeoutAfter<T>(this Task<T> task, TimeSpan timeout)
        {
            using (var cts = new CancellationTokenSource())
            {
                var delayTask = Task.Delay(timeout, cts.Token);
                var completedTask = await Task.WhenAny(task, delayTask);
                if (completedTask == delayTask)
                {
                    //throw new TimeoutException("Time Out");
                }
                cts.Cancel(); // 取消 Delay 任务
                return await task; // 返回原始任务结果
            }
        }
    }
}
